package com.security.wxlogin.conf;

import com.security.wxlogin.util.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname WXAuthenticationManager
 * @Description 微信认证管理器
 * @Date 2020/4/24 0024 17:28
 * @Created by 埔枘
 */
@Slf4j
public class WXAuthenticationManager implements AuthenticationManager {

    private static final List<GrantedAuthority> AUTHORITIES = new ArrayList<>();

    static {
        AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER"));
    }
    /**
     * 获取 用户信息 的 API
     */
    private final static String USERINFO_TOKEN = "https://api.weixin.qq.com/sns/userinfo";


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (authentication.getPrincipal() != null && authentication.getCredentials() != null) {
            try {
                Map<String, String> userInfo = getUserInfo((String) authentication.getPrincipal(), (String) (authentication.getCredentials()));
                log.info("用户信息:{}",userInfo);
                if(userInfo.get("errcode") == null){
                    return new UsernamePasswordAuthenticationToken(userInfo,
                            null, AUTHORITIES);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        throw new BadCredentialsException("Bad Credentials");
    }

    /**
     * 正常返回:
     * {
     * "openid":"OPENID",
     * "nickname":"NICKNAME",
     * "sex":1,
     * "province":"PROVINCE",
     * "city":"CITY",
     * "country":"COUNTRY",
     * "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
     * "privilege":[
     * "PRIVILEGE1",
     * "PRIVILEGE2"
     * ],
     * "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
     *
     * }
     *
     * 错误返回:
     * {
     * "errcode":40003,"errmsg":"invalid openid"
     * }
     */
    private Map<String, String> getUserInfo(String accessToken,String openId) throws IOException {
        Map<String,String> info = new HashMap<>();
        info.put("access_token",accessToken);
        info.put("openid",openId);
        return (Map<String, String>) HttpRequestUtil.get(USERINFO_TOKEN, info,Map.class);
    }
}
